// work/pages/clockIn/clockIn.js
const app = getApp()
var bmap = require('../../../lib/bmap-wx'); //bmap-wx.js文件存放路径
var BMap = new bmap.BMapWX({
  ak: 'd2KjPsoWTSGWv83Nif3XD7CuRCLxCrFr' //百度地图密钥
});
var startTimer = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: true, //false打卡成功
    timer: '00:00', //时间
    startTimer: null, //计时器
    signIn: {
      signTime: '',
      memberId: app.globalData.memberId,
      signAddress: '',
      signLats: '',
      signLongs: '',
      signDetail: '', //备注
      signKind: 0, //  0 每日签到  1 外出打卡
      signStatus: '', //  0 不在范围内  1 在范围内
      signType: '', //  0 上班卡  1 下班卡
      lateTime: '' //  0迟到  1 早退  2 正常
    },
    latitude: 43.869759896782, //首次加载维度
    longitude: 125.36485025603, //首次加载的经度
    mapName: "", //选点的位置
    todayList: { // 今日签到记录
      am: [],
      pm: [],
    },
    singFlag: false, // true 已打卡 false 未打卡

    amTime: '08:30', //上班打卡时间
    pmTime: '17:30', //下班打卡时间
  },


  // 选择 考勤打卡  外出打卡
  navHandle(e) {
    var flag = e.currentTarget.dataset.flag,
      that = this,
      signIn = this.data.signIn;
    signIn.signKind = flag
    signIn.signDetail = ''
    if (flag == 1) {
      wx.showLoading({
        title: '定位中...',
      })
      BMap.regeocoding({
        success(res) {
          wx.hideLoading()
          console.log(res);
          signIn.signTime = that.data.timer
          signIn.signLats = res.originalData.result.location.lat
          signIn.signLongs = res.originalData.result.location.lng
          signIn.signAddress = res.originalData.result.sematic_description
          console.log(that.data.latitude, that.data.longitude, signIn.signLats, signIn.signLongs);
        },
        fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '定位失败,下拉刷新',
            icon: 'none'
          })
          console.log(res);
        }
      })
    }
    console.log(signIn);
    this.setData({
      signIn,
      singFlag: false
    })
  },

  // 判断时间   0 判断上班时间   1 判断下班时间   true  迟到或早退
  checkTime(flag) {
    let time = new Date();
    let hours = time.getHours() < 10 ? ('0' + time.getHours()) : time.getHours();
    let minutes = time.getMinutes() < 10 ? ('0' + time.getMinutes()) : time.getMinutes();
    var timer = hours + ':' + minutes,
      endTime = flag == 0 ? this.data.amTime : this.data.pmTime
    console.log(timer);

    var startTime = new Date(`2023/11/11 ${timer}`).getTime(),
      endTime = new Date(`2023/11/11 ${endTime}`).getTime();
    console.log(startTime);
    console.log(endTime);
    if (flag == 0) {
      return startTime > endTime
    } else if (flag == 1) {
      return startTime < endTime
    }


  },



  // 点击打卡
  daka() {
    var latitude = this.data.latitude,
      longitude = this.data.longitude,
      that = this,
      signIn = this.data.signIn,
      str = '',
      todayList = this.data.todayList;
    console.log(latitude);
    console.log(longitude);
    console.log(signIn);


    if (signIn.signKind == 0) { //考勤打卡
      if (signIn.signStatus == 0 && signIn.signType == 0) { //范围外
        str = '您当前打卡位置尚未进入考勤范围'
      } else if (signIn.signType == 1 && this.checkTime(1) && todayList.pm.length == 0) {
        str = '您当前打卡时间属于早退'
      } else if (todayList.am.length != 0 && signIn.signType == 0) {
        str = '您已完成上班打卡'
      } else if (todayList.pm.length != 0 && signIn.signType == 1) {
        str = '您已完成下班打卡'
      }
      if (str != '') {
        wx.showModal({
          title: '通知',
          content: str,
          confirmText: '仍要打卡',
          cancelText: '取消',
          confirmColor: '#999',
          cancelColor: '#2A6DDD',
          complete: (res) => {
            if (res.confirm) {
              this.getdakaInfo()
            }
          }
        })
      } else {
        this.getdakaInfo()
      }
    } else if (signIn.signKind == 1) {
      console.log('外出');
      this.getdakaInfo()
    }

  },

  // 考勤打卡 获取定位
  getdakaInfo() {
    var that = this,
      signIn = this.data.signIn
    wx.showLoading({
      title: '定位中...',
    })
    BMap.regeocoding({
      success(res) {
        wx.hideLoading()
        console.log(res);
        signIn.signTime = that.data.timer
        signIn.signLats = res.originalData.result.location.lat
        signIn.signLongs = res.originalData.result.location.lng
        signIn.signAddress = res.originalData.result.sematic_description
        console.log(that.data.latitude, that.data.longitude, signIn.signLats, signIn.signLongs);
        var juliNum = that.juli(that.data.latitude, that.data.longitude, signIn.signLats, signIn.signLongs)
        console.log(juliNum);
        if (juliNum > 500 && signIn.signKind == 0) {
          wx.showToast({
            title: '打卡距离大于500m',
            icon: 'none'
          })
          that.clockHandle(signIn)
          return
        } else {
          that.clockHandle(signIn)
        }
      },
      fail(res) {
        wx.hideLoading()
        wx.showToast({
          title: '定位失败,下拉刷新',
          icon: 'none'
        })
        console.log(res);
      }
    })
  },


  // 发送打卡请求
  clockHandle(obj) {
    var url = app.globalData.url + 'main/addDailySignIn',
      that = this;
    wx.showLoading({
      title: '',
    })
    console.log(obj);
    // return
    that.setData({
      singFlag: true,
      signIn: obj
    })
    app.wxRequest(url, obj, res => {
      console.log(res);
      if (res.flag) {
        wx.showModal({
          title: '打卡',
          content: '恭喜您,打卡成功',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              that.setData({
                singFlag: true,
                signIn: obj
              })
            }
          }
        })
      } else {
        wx.showModal({
          title: '打卡',
          content: '打卡失败,请重试',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {}
          }
        })
      }
      wx.hideLoading()
    })

  },

  // 获取公司定位
  getGsInfo(keyWord) {
    var that = this;
    console.log(keyWord);
    BMap.search({
      "query": keyWord,
      fail(res) {
        console.log(res);
        wx.showToast({
          title: '定位失败,下拉刷新',
          icon: 'none'
        })
      },
      success(res) {
        console.log(res);
        that.setData({
          latitude: res.originalData.results[0].location.lat,
          longitude: res.originalData.results[0].location.lng,
        })
      },
    });
  },

  getMyInfo() {
    var that = this,
      signIn = this.data.signIn;
    wx.showLoading({
      title: '定位中...',
    })
    BMap.regeocoding({
      success(data) {
        console.log(data);
        signIn.signLats = data.originalData.result.location.lat
        signIn.signLongs = data.originalData.result.location.lng
        var juliNum = that.juli(that.data.latitude, that.data.longitude, signIn.signLats, signIn.signLongs)
        console.log(juliNum);
        signIn.signStatus = juliNum > 500 ? 0 : 1
        that.setData({
          signIn
        })
        wx.hideLoading()
      },
      fail(res) {
        wx.showToast({
          title: '定位失败,下拉刷新',
          icon: 'none'
        })
        console.log(res);
        wx.hideLoading()
      }
    })


  },


  //计算两点之间的距离
  juli(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    return s * 1000
  },
  // 获取指定地点定位
  getLocation() {
    let that = this; //防止this指向问题
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      //错误信息
      fail: function () {
        wx.showToast({
          title: '定位失败,下拉刷新',
          icon: 'none'
        })
        console.log(err);
      }
    })
  },

  // 实时时间
  timeData() {
    let time = new Date();
    let hours = time.getHours() < 10 ? ('0' + time.getHours()) : time.getHours();
    let minutes = time.getMinutes() < 10 ? ('0' + time.getMinutes()) : time.getMinutes();
    let seconds = time.getSeconds() < 10 ? ('0' + time.getSeconds()) : time.getSeconds();
    var timer = hours + ':' + minutes + ':' + seconds,
      signIn = this.data.signIn;
    signIn.signType = time.getHours() < 12 ? 0 : 1;

    console.log(this.checkTime(1));
    if (signIn.signType == 0) { //上班打卡
      signIn.lateTime = this.checkTime(0) ? 0 : 2 //是否迟到
    } else if (signIn.signType == 1) {
      signIn.lateTime = this.checkTime(1) ? 1 : 2 // 是否早退
    }
    console.log(signIn);
    this.setData({
      timer,
      signIn
    })
  },

  // 获取今日签到记录
  getTodaySignList() {
    var url = app.globalData.url + 'main/getTodayDailySignIn',
      that = this,
      todayList = { // 今日签到记录
        am: [],
        pm: [],
      };
    app.wxRequest(url, {
      memberId: app.globalData.memberId
    }, res => {
      if (res.flag) {
        res.data.reverse()
        console.log(res.data);
        res.data.forEach(item => {
          item.time = item.signTime.split(' ')[1].slice(0, 5)
          if (item.signType == 0) {
            todayList.am.push(item)
          } else {
            todayList.pm.push(item)
          }
        })
        console.log(todayList);
        that.setData({
          todayList
        })
      }
    })

  },


  // 查看打卡记录
  checkList() {
    wx.navigateTo({
      url: '/work/pages/clockIn_record/clockIn_record',
    })
  },

  // 关闭成功 弹窗
  closeHandle() {
    this.setData({
      singFlag: false
    })
    this.onLoad()
  },

  inputHandle(e) {
    console.log(e);
    var str = 'signIn.signDetail',
      value = e.detail.value;

    this.setData({
      [str]: value
    })
    console.log(this.data);
  },

  // 获取签到时间 设置
  getSignTime() {
    var url = app.globalData.url + 'main/getSignInSetting',
      that = this,
      amTime = '',
      pmTime = '';
    app.wxRequest(url, {}, res => {
      if (res.flag) {
        console.log(res);
        amTime = res.data.signInSettings[0].signInTime.split(' ')[1].slice(0, 5)
        pmTime = res.data.signInSettings[1].signInTime.split(' ')[1].slice(0, 5)

      } else {
        amTime = '08:30'
        pmTime = '17:30'
      }
      that.setData({
        amTime,
        pmTime
      })
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getSignTime()
    console.log(this.checkTime(1));
    clearInterval(startTimer)
    this.timeData();
    this.getMyInfo()
    this.getTodaySignList()


    startTimer = setInterval(() => {
      this.timeData();
    }, 1000);
    // this.getGsInfo("华安大厦(临河街)") //获取公司经纬度
    wx.stopPullDownRefresh()

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(startTimer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log(11);
    clearInterval(startTimer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onLoad()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})